package com.itheima.reggie.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.ReggieException;
import com.itheima.reggie.common.ServerResultVO;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * category
 * @author 武帅丞
 * @date 2024/9/13
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public ServerResultVO<String> add(@RequestBody Category category) {
        categoryService.save(category);
        log.info("add category:{}", category);
        return ServerResultVO.success("successfully added category");
    }

    @GetMapping("/page")
    public ServerResultVO<Page> page(int page, int pageSize) {
        Page<Category> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, queryWrapper);
        return ServerResultVO.success(pageInfo);
    }

    /**
     * dish get list
     * @param category
     * @return categoryList
     */
    @GetMapping("/list")
    public ServerResultVO<List<Category>> list(Category category) {
        if (category.getType() == null) {
            throw new ReggieException("null type for list query!");
        }
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getType, category.getType());
        queryWrapper.orderByDesc(Category::getSort).orderByAsc(Category::getUpdateTime);
        List<Category> categoryList = categoryService.list(queryWrapper);
        return ServerResultVO.success(categoryList);
    }

    @DeleteMapping
    public ServerResultVO<String> delete(Long ids) {
        log.info("delete category:{}", ids);
        categoryService.remove(ids);
        return ServerResultVO.success("successfully deleted");
    }

    @PutMapping
    public ServerResultVO<String> update(@RequestBody Category category) {
        log.info("update category:{}", category);
        categoryService.updateById(category);
        return ServerResultVO.success("successfully updated");
    }
}
